package per.ace.validate.web;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import per.ace.validate.common.MyException;
import per.ace.validate.config.DemoException;
import per.ace.validate.entity.Student;

/**
 * @program: springbootDemo
 * @description: @ModelAttribute：在Model上设置的值，对于所有被 @RequestMapping 注解的方法中，都可以通过 ModelMap 获取
 * @author: ace
 * @Date: 2020-06-12 10:44
 */
@RestController
public class TestController {

    /**
     * 方法1
     * 通过参数 ModelMap 获取controllerAdvice构建的属性
     *
     * @param modelMap
     * @return
     */
    @GetMapping("home")
    public String home(ModelMap modelMap) {
        Object author = modelMap.get("author");
        System.out.println(author);
        return author.toString();
    }


    /**
     * 方法2
     * 或者 通过@ModelAttribute获取
     *
     * @param author
     * @return
     */
    @GetMapping("test")
    public String home(@ModelAttribute("author") String author) {
        System.out.println(author);
        return author;
    }


    /**
     * 测试接受参数
     *
     * @param student  接口入参
     * @param modelMap controllerAdvice 构建
     * @return
     */
    @GetMapping("alex")
    public String alex(@RequestBody Student student, ModelMap modelMap) {
        System.out.println(student.getGrade());
        Object author = modelMap.get("author");
        System.out.println(author);
        return author.toString();
    }


    @GetMapping("say")
    public Student say() {
        return new Student("alex", "一年级");
    }

    /**
     * @return
     * @throws Exception
     */
    @GetMapping("error")
    public int error() {
        if (true) {
            throw new DemoException("error", 404);
        }
        return 1;
    }
}
